import CryptoJS from 'crypto-js'
import JSEncrypt from 'jsencrypt'

function parse(text) {
  return CryptoJS.enc.Latin1.parse(text)
}

export function aesEncrypt(origin, key, iv) {
  let config = {
    iv: parse(iv),
    mode: CryptoJS.mode.CBC
  }
  let encrypted = CryptoJS.AES.encrypt(origin, parse(key), config)
  return encrypted.toString()
}

export function aesDecrypt(encrypted, key, iv) {
  let config = {
    iv: parse(iv),
    mode: CryptoJS.mode.CBC
  }
  let decrypted = CryptoJS.AES.decrypt(encrypted, parse(key), config)
  return decrypted.toString(CryptoJS.enc.Utf8)
}

export function rsaEncrypt(publicKey, input) {
  let encrypter = new JSEncrypt()
  encrypter.setPublicKey(publicKey)
  return encrypter.encrypt(input)
}

export function hash(input) {
  return CryptoJS.SHA256(input).toString()
}
